/**
 * Copyright &copy; 2016 splat  All rights reserved.
 */
package com.osig.sys.web;

import java.io.IOException;
import java.util.Map;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.common.common.ResultData;
import com.common.util.ConfigUtil;
import com.common.util.Tool;
import com.google.common.collect.Maps;
import com.osig.common.security.shiro.session.SessionDAO;
import com.osig.common.servlet.ValidateCodeServlet;
import com.osig.common.web.BaseController;
import com.osig.sys.security.SystemAuthorizingRealm.Principal;

import com.osig.util.CacheUtils;
import com.osig.util.CookieUtils;
import com.osig.util.StringUtils;
import com.osig.util.UserUtils;
import com.rbac.util.CommonUtil;
import com.user.common.CodeConts;
import com.user.entity.emp.Emp;
import com.user.entity.emp.EmpVO;
import com.user.service.emp.EmpService;





/**
 * 登录Controller
 * @author splat
 * @version 2013-5-31
 */
@Controller
public class LoginController extends BaseController{
	
	@Autowired
	private SessionDAO sessionDAO;
	/*@Autowired
	private EmpService empService;*/
	/**
	 * 验证码 
	 * @throws IOException 
	 */
	@RequestMapping(value = "code")
	public void code(HttpServletRequest request, HttpServletResponse response) throws IOException{
		ValidateCodeServlet validateCodeServlet = new ValidateCodeServlet();
		validateCodeServlet.createImage(request, response);
	}
	
	/**
	 * 验证码 
	 * @throws IOException 
	 */
	@ResponseBody
	@RequestMapping(value = "checkCode")
	public String checkCode(String validateCode,HttpServletRequest request) throws IOException{
		 if(ValidateCodeServlet.validate(request, validateCode)){
			return "true"; 
		 }
		 return "false";
	}
	
	/**
	 * 管理登录
	 * @throws Exception 
	 */
	@RequestMapping(value = "login", method = RequestMethod.GET)
	public String login(HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {
		Principal principal = UserUtils.getPrincipal();
		// 如果已经登录，则跳转到管理首页
		if(principal != null && !principal.isMobileLogin()){
			EmpVO emp = UserUtils.getUser();
			model.addAttribute("emp", emp);
			return "redirect:";
		}
		return "redirect:" + ConfigUtil.getValue("sso.web.site");
	}
	
	@RequestMapping(value = "index" )
	public String index1(Model model, HttpServletRequest request, HttpServletResponse response) {
		EmpVO emp = UserUtils.getUser();
		model.addAttribute("emp", emp);
		return "modules/sys/sysIndex";
	}
	   /**
     * @Title 登出PC
     * @method  logoutPC
     * @param request
     * @param response
     * @throws
     * @author  sunyan
     * @date    2017-08-11
     */
	/*@RequestMapping(value = { "logoutPC"})
	@ResponseBody
	  public String logoutPC(HttpServletRequest request,HttpServletResponse response) {
        ResultData resultData = new ResultData();
        CommonUtil.logOut(request, response);
        String token = Tool.ReadCookieMap(request).get("token").getValue();
        try {
            String jwtCode = empService.verificationToken(token).getCode();

            Emp emp = empService.selectByCode(jwtCode);
            if (emp == null) {

                resultData.setStatus(CodeConts.PARAM_LEGAL);
                resultData.setMessage("用户不存在");
                response.sendRedirect(ConfigUtil.getValue("sso.web.site"));
            }
            //4、删除cookie
            Cookie cookie = new Cookie("token",null);
            cookie.setMaxAge(0);
            cookie.setPath("/");
            cookie.setDomain(ConfigUtil.getValue("sso.web.domain"));
            response.addCookie(cookie);
            //5、返回
            resultData.setStatus(CodeConts.SUCCESS);
            resultData.setMessage("登出成功 ");     
            Subject subject = SecurityUtils.getSubject();
            subject.logout();
            return "redirect:" + ConfigUtil.getValue("sso.web.site");
        } catch (Exception e) {
            resultData.setStatus(CodeConts.FAILURE);
            resultData.setMessage("登出异常");
            return "redirect:" + ConfigUtil.getValue("sso.web.site");
        }
    }*/
	/**
	 * 登录失败，真正登录的POST请求由Filter完成
	 */
	@RequestMapping(value = "login", method = RequestMethod.POST)
	public String loginFail(HttpServletRequest request, HttpServletResponse response, Model model) {
		Principal principal = UserUtils.getPrincipal();
		// 如果已经登录，则跳转到管理首页
		if(principal != null){
			return "redirect:";
		}
		return "modules/sys/sysLogin";
	}

	/**
	 * 登录成功，进入管理首页
	 */
	@RequiresPermissions("user")
	@RequestMapping(value = "")
	public String index(Model model,HttpServletRequest request, HttpServletResponse response) {
		Principal principal = UserUtils.getPrincipal();
		EmpVO emp = UserUtils.getUser();
		model.addAttribute("emp", emp);
		// 登录成功后，验证码计算器清零
		isValidateCodeLogin(principal.getLoginName(), false, true);
		if (logger.isDebugEnabled()){
			logger.debug("show index, active session size: {}", sessionDAO.getActiveSessions(false).size());
		}
		return "modules/sys/sysIndex";
	}
	
	/**
	 * 获取主题方案
	 */
	@RequestMapping(value = "/theme/{theme}")
	public String getThemeInCookie(@PathVariable String theme, HttpServletRequest request, HttpServletResponse response){
		if (StringUtils.isNotBlank(theme)){
			CookieUtils.setCookie(response, "theme", theme);
		}else{
			theme = CookieUtils.getCookie(request, "theme");
		}
		return "redirect:"+request.getParameter("url");
	}
	
	/**
	 * 是否是验证码登录
	 * @param useruame 用户名
	 * @param isFail 计数加1
	 * @param clean 计数清零
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static boolean isValidateCodeLogin(String useruame, boolean isFail, boolean clean){
		Map<String, Integer> loginFailMap = (Map<String, Integer>)CacheUtils.get("loginFailMap");
		if (loginFailMap==null){
			loginFailMap = Maps.newHashMap();
			CacheUtils.put("loginFailMap", loginFailMap);
		}
		Integer loginFailNum = loginFailMap.get(useruame);
		if (loginFailNum==null){
			loginFailNum = 0;
		}
		if (isFail){
			loginFailNum++;
			loginFailMap.put(useruame, loginFailNum);
		}
		if (clean){
			loginFailMap.remove(useruame);
		}
		return loginFailNum >= 3;
	}
}